<template>

    <el-button type="primary" @click="dialogVisible = true">新增 </el-button>
    <el-button type="primary">删除 </el-button>


    <el-form :model="search" :inline="true">
        <el-form-item label="商品名称">
            <el-input v-model="search.GoodName" clearable></el-input>
        </el-form-item>
        <el-form-item label="生产批次">
            <el-input v-model="search.ProductDate" clearable></el-input>
        </el-form-item>
        <el-form-item label="保质期">
            <el-input v-model="search.UserRname" clearable></el-input>
        </el-form-item>
        <el-form-item label="生产许可证">
            <el-input v-model="search.ProductCode" clearable></el-input>
        </el-form-item>
        <el-form-item label="生产企业">
            <el-input v-model="search.ProductBusiness" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建人">
            <el-input v-model="search.AddName" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
            <el-input v-model="search.AddDateTime" clearable></el-input>
        </el-form-item>
        <el-form-item label="修改人">
            <el-input v-model="search.DelName" clearable></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="showAll()">查询</el-button>
        </el-form-item>
    </el-form>

    <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sourceId" label="序号"></el-table-column>
        <el-table-column prop="goodName" label="商品名称"></el-table-column>
        <el-table-column prop="productDate" label="生产批次" width="150"></el-table-column>
        <el-table-column prop="userRname" label="保质期">
            <template #default="scope">
                {{ scope.row.userRname }}

            </template>
        </el-table-column>
        <el-table-column prop="productCode" label="生产许可证" width="150"></el-table-column>
        <el-table-column prop="productBusiness" label="生产企业" width="150"></el-table-column>
        <el-table-column prop="infoCount" label="信息完善度" width=150>
            <template #default="scope">
                {{ scope.row.infoCount }}%

            </template>
        </el-table-column>
        <el-table-column prop="addName" label="创建人"></el-table-column>
        <el-table-column prop="addDateTime" label="创建时间" width="180">
            <template #default="scope">
                {{ scope.row.addDateTime.replace("T", " ") }}

            </template>



        </el-table-column>
        <el-table-column prop="sourceId" label="操作" width="240" fixed="right">

            <template #default="scope">
                <el-button link type="primary" @click="handleDetail(scope.row.sourceId)">详情</el-button>
                <el-button link type="primary" @click="handleEdit(scope.row.sourceId)">编辑</el-button>
                <el-button link type="primary" @click="handleExport(scope.row.sourceId)">导出溯源码</el-button>
                <el-button link type="primary" @click="handleDelete(scope.row.sourceId)">删除</el-button>
            </template>

        </el-table-column>
    </el-table>

    <!-- 基本信息添加对话框 -->
    <el-dialog v-model="dialogVisible" title="基本信息" width="500" :before-close="handleClose">
        <span>

            <el-form :model="sources" label-width="120px" ref="ruleFormRef" style="max-width: 600px" :rules="rules"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="商品名称" prop="goodName">
                    <el-input v-model="sources.goodName" />
                </el-form-item>
                <el-form-item label="生产批次" prop="productDate">
                    <el-input v-model="sources.productDate" />
                </el-form-item>
                <el-form-item label="保质期" prop="userRname">
                    <el-input v-model="sources.userRname" />
                </el-form-item>
                <el-form-item label="生产许可证" prop="productCode">
                    <el-input v-model="sources.productCode" />
                </el-form-item>
                <el-form-item label="生产企业" prop="productBusiness">
                    <el-input v-model="sources.productBusiness" />
                </el-form-item>
                <el-form-item label="封面图">
                    <!-- <el-input v-model="sources.sourceImage" /> -->
                    <el-upload class="avatar-uploader" action="http://localhost:5240/api/SourceList/Upload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="sources.sourceImagefiles" :src="sources.sourceImagefiles" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>


            </el-form>



        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>

            </div>
        </template>
    </el-dialog>
    <!-- 基本信息修改对话框 -->
    <el-dialog v-model="dialogVisibleupdate" title="基本信息" width="500" :before-close="handleClose">
        <span>

            <el-form :model="sources" label-width="120px" ref="ruleFormRef" style="max-width: 600px" :rules="rules"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="商品名称" prop="goodName">
                    <el-input v-model="sources.goodName" />
                </el-form-item>
                <el-form-item label="生产批次" prop="productDate">
                    <el-input v-model="sources.productDate" />
                </el-form-item>
                <el-form-item label="保质期" prop="userRname">
                    <el-input v-model="sources.userRname" />
                </el-form-item>
                <el-form-item label="生产许可证" prop="productCode">
                    <el-input v-model="sources.productCode" />
                </el-form-item>
                <el-form-item label="生产企业" prop="productBusiness">
                    <el-input v-model="sources.productBusiness" />
                </el-form-item>
                <el-form-item label="封面图">
                    <!-- <el-input v-model="sources.sourceImage" /> -->
                    <el-upload class="avatar-uploader" action="http://localhost:5240/api/SourceList/Upload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="sources.sourceImagefiles" :src="sources.sourceImagefiles" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>


            </el-form>



        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>

            </div>
        </template>
    </el-dialog>




    <!-- 导出溯源码对话框 -->
    <el-dialog v-model="dialogVisibleexport" title="导出设置" width="500" :before-close="handleClose">

        <!-- <el-form>
            <el-form-item label="导出数量">
                <el-input v-model="exportnumber"></el-input>
            </el-form-item>
        </el-form> -->
        <QRcode />


        <template #footer>
            <div class="dialog-footer">

                <el-button type="primary" @click="addSource">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, inject, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router'
import { type AxiosStatic } from 'axios'
const dialogVisible = ref(false)//新增对话框

const axios = inject('axios') as AxiosStatic
const router = useRouter()
const route = useRoute()
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
import QRcode from '../SourceMan/QRCode.vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()


const dialogVisibleexport = ref(false)
const imageUrl = ref('')
//定义表数据
const tableData = ref([])

//加载生命周期钩子
onMounted(() => {
    showAll()

    //获取当前年月日当生产批次号 
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let productCode = year + "0" + month + "0" + day;
    sources.value.productDate = productCode;
})

//查询条件 string? GoodName,string? ProductDate,string? UserRname,string? ProductCode,string? ProductBusiness,string? AddName,string? AddDateTime,string? DelName
const search = ref({
    GoodName: "",
    ProductDate: "",
    UserRname: "",
    ProductCode: "",
    ProductBusiness: "",
    AddName: "",
    AddDateTime: "",
    DelName: "",
    DelDateTime: ""
})



//加载数据
const showAll = () => {
    //获取数据
    axios.get('SourceList/GetSourceList', {
        params: {
            GoodName: search.value.GoodName,
            ProductDate: search.value.ProductDate,
            UserRname: search.value.UserRname,
            ProductCode: search.value.ProductCode,
            ProductBusiness: search.value.ProductBusiness,
            AddName: search.value.AddName,
            AddDateTime: search.value.AddDateTime,
            DelName: search.value.DelName,
            DelDateTime: search.value.DelDateTime

        }
    }).then((res) => {
        console.log(res.data)
        tableData.value = res.data.data
    })
}

//添加溯源管理实体
const sources = ref({
    //"sourceId": 0,
    "goodName": "",
    "productDate": "",
    "userRname": "",// 保质期
    "productCode": "",//生产许可证
    "productBusiness": "",
    "infoCount": 0,
    "sourceImage": "",
    "sourceImagefiles": "",
    "checkImages": "",
    "addName": "",
    // "addDateTime": "",
    // "delName": "",
    // "delDateTime": ""
})

sources.value.length = 0
//表单验证
const rules = reactive<FormRules<sources>>({
    goodName: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    productDate: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    userRname: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    productCode: [
        { required: true, message: '请输入', trigger: 'blur' },
        { min: 0, max: 30, message: '最多输入30个字符', trigger: 'blur' },
    ],
    productBusiness: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
});
//表单提交

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // console.log('submit!')
            //添加数据   /api/SourceList/AddSource
            const addSource = () => {
                //  console.log(sources.value)
                axios.post('/SourceList/AddSource', sources.value).then((res) => {
                    if (res.data.code == 1) {
                        ElMessage({
                            message: '添加成功',
                            type: 'success',
                        })
                        dialogVisible.value = false
                        showAll()
                    } else {
                        ElMessage.error('添加失败')
                        return;

                    }
                })

            }







        } else {
            console.log('error submit!', fields)
        }
    })
}




//图片上传方法
const handleAvatarSuccess = (val: any) => {
    sources.value.sourceImagefiles = 'http://localhost:5240/' + val
    sources.value.sourceImage = val
    console.log(val)

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('请上传正确的格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能大于 2MB!')
        return false
    }
    return true
}



//删除数据  DelSource 提示删除 
const handleDelete = (id: any) => {
    ElMessageBox.confirm('是否要删除该商品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            axios.delete('/SourceList/DelSource', {
                params: {
                    SourceId: id
                }
            }).then((res) => {
                if (res.data.data == 1) {
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    })
                    showAll()
                } else {
                    ElMessage.error('删除失败')
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}

//批量删除
const handleSelectionChange = () => {

}





const dialogVisibleupdate = ref(false)
//修改信息弹框
const handleEdit = (val: any) => {
    dialogVisibleupdate.value = true
    showById(val)
}


//编辑---反填
//根据id反填商品信息

const showById = (val: any) => {
    //获取数据
    axios.get('SourceList/GetSourceById?id=' + val).then((res) => {
        console.log(res.data)
        sources.value = res.data.data

        sources.value.sourceImagefiles = "http://localhost:5240" + res.data.data.sourceImage

        //

    })
}

//编辑数据
// const handleEdit = (id: any) => {
//     axios.post('/SourceList/GetSource', { id: id }).then((res) => {
//         if (res.data.code == 1) {
//             sources.value = res.data.data
//             dialogVisible.value = true
//         } else {
//             ElMessage.error('获取数据失败')
//         }
//     })
// }

//查询数据




//关闭弹框
const handleClose = (done: () => void) => {
    ElMessageBox.confirm('是否要关闭对话框?')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}

//跳转详情页面 
const handleDetail = (id: any) => {
    router.push({
        path: '/SourceDetail',
        query: {
            id: id
        }
    })
}

const exportnumber = ref(0)




//导出溯源码
const handleExport = (val: any) => {
    dialogVisibleexport.value = true
}










</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
